package com.soledroid;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.soledroid.BrowseActivity.MyLocationListener;
import com.soledroid.Model.Dish;
import com.soledroid.Model.Stall;
import com.soledroid.Model.User;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class DashboardActivity extends Activity {
	private LocationManager mLocationManager;
	private LocationListener mLocationListener;
	private String mProvider = LocationManager.GPS_PROVIDER;
	private Location l;
	
	private String nearName = "";
	private int nearId = 0;
	
	private Button mBrowseBtn;
	private Button mMapBtn;
	private Button mProfileBtn;
	private Button mRegisterBtn;
	private TextView mNearestCanteenView;
	ArrayList<Dish> promotedDishes;
	
	static final int DIALOG_NOT_REGISTED_USER = 1;
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dashboard);
        
        if(isRegisteredUser()){
        	//showDialog(DIALOG_REGISTED_USER);
        } else{
        	showDialog(DIALOG_NOT_REGISTED_USER);
        }
        
        mBrowseBtn = (Button) findViewById(R.id.browse_btn);
        mMapBtn = (Button) findViewById(R.id.map_btn);
        mProfileBtn = (Button) findViewById(R.id.profile_btn);
        mRegisterBtn = (Button) findViewById(R.id.register_btn);
        mNearestCanteenView = (TextView) findViewById(R.id.nearest_canteen);
        
        mBrowseBtn.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		Intent i = new Intent(getApplicationContext(), BrowseActivity.class); 
        		DashboardActivity.this.startActivity(i);
        	}
        });
        
        mMapBtn.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		Intent i = new Intent(getApplicationContext(), MapViewActivity.class); 
        		DashboardActivity.this.startActivity(i);
        	}
        });
        
        mProfileBtn.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		Intent i = new Intent(getApplicationContext(), ProfileActivity.class); 
        		i.putExtra("id", getSharedPreferences("me", MODE_PRIVATE).getInt("id", 1));
        		DashboardActivity.this.startActivity(i);
        	}
        });
        
        mRegisterBtn.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		Intent i = new Intent(getApplicationContext(), RegisterActivity.class); 
        		DashboardActivity.this.startActivity(i);
        	}
        });
        
        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		mLocationListener = new MyLocationListener();
		if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			mProvider = LocationManager.NETWORK_PROVIDER;
		}
		mLocationManager.requestLocationUpdates(mProvider, 0,// MIN_TIME_TO_UPDATE,
				0,// MIN_DIST_TO_UPDATE,
				mLocationListener);
		l = mLocationManager.getLastKnownLocation(mProvider);
        
        
        promotedDishes = this.fetchPromotedDishes();
        
        mNearestCanteenView.setText(nearName);
        mNearestCanteenView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent i = new Intent(getApplicationContext(), CanteenActivity.class);
				i.putExtra("name", nearName);
				i.putExtra("id", nearId);
				DashboardActivity.this.startActivity(i);
				
			}
        	
        });
        
        Gallery g = (Gallery) findViewById(R.id.offers_gallery);
        g.setAdapter(new ImageAdapter(this));
        
        g.setOnItemClickListener(new OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        		
        		Intent i = new Intent(getApplicationContext(),DishActivity.class);

				Dish dish = promotedDishes.get(position);
				i.putExtra("id", dish.getId());
				i.putExtra("name", dish.getName());

				DashboardActivity.this.startActivity(i);
        	}
        });
        
        if(!isNetworkAvailable()) {
			Toast.makeText(getApplicationContext(), 
					"Network is currently unavailable", Toast.LENGTH_LONG).show();
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		refresh();
		if(!isNetworkAvailable()) {
			Toast.makeText(getApplicationContext(), 
					"Network is currently unavailable", Toast.LENGTH_LONG).show();
		}
	}
	
	protected Dialog onCreateDialog(int id) {
	    switch(id) {
	    case DIALOG_NOT_REGISTED_USER:
	    	return new AlertDialog.Builder(DashboardActivity.this)
	    		.setTitle("you are not a registered user.")
	    		.setNegativeButton("Register now", new DialogInterface.OnClickListener() {
	    			public void onClick(DialogInterface dialog, int id) {
	    				Intent i = new Intent(getApplicationContext(), RegisterActivity.class); 
	            		DashboardActivity.this.startActivity(i);
	    			}
	    		})
	    		.create();
	    } 
	    
	    return null;
	}
	
	public boolean isRegisteredUser(){
		String android_id = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID);
		
		try {
			URL url = new URL("http://soledroid.huytoan.com/udid/" + android_id);
			URLConnection tc = url.openConnection();
			tc.setUseCaches(true);
			BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));

			String line;
			while ((line = in.readLine()) != null) {
                JSONArray ja = new JSONArray(line);
 
                for (int i = 0; i < ja.length(); i++) {
                    JSONObject jo = (JSONObject) ja.get(i);
                    if(jo.getString("username") != null){
                    	SharedPreferences settings = getSharedPreferences("me", MODE_PRIVATE);
                    	SharedPreferences.Editor editor = settings.edit();
                    	
                    	editor.putInt("id", jo.getInt("id"));
                    	editor.putString("username", jo.getString("username"));
                    	editor.putString("fullname", jo.getString("fullname"));
                    	editor.putString("image", jo.getString("image"));
                    	editor.putString("udid", android_id);
                    	
                    	editor.commit();
                    } else{
                    	
                    	return false;
                    }
                }
            }
        } catch (Exception e) {
            return true;
        } 
        
        return true;
	}
	
	public ArrayList<Dish> fetchPromotedDishes()
	{
		ArrayList<Dish> listItems = new ArrayList<Dish>();

		try {
			URL url = new URL("http://soledroid.huytoan.com/checkin?user_id=1&latitude=" + l.getLatitude() + "&longitude=" + l.getLongitude());
			URLConnection tc = url.openConnection();
			tc.setUseCaches(true);
			BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));

			String line;
			while ((line = in.readLine()) != null) {
				JSONObject json = new JSONObject(line);
				JSONObject nearestCanteen = json.getJSONObject("nearestCanteen");
				nearName = nearestCanteen.getString("name");
				nearId = nearestCanteen.getInt("id");
				
				JSONArray ja = json.getJSONArray("nearestOffers");

				for (int i = 0; i < ja.length(); i++) {
					JSONObject jo = (JSONObject) ja.get(i);

					Dish dish = new Dish(jo.getInt("id"), jo.getString("name"), jo.getString("image"),
							jo.getString("description"), jo.getString("price"), jo.getInt("stall_id"),
							jo.getInt("on_promotion") == 1, jo.getDouble("rating"));
					listItems.add(dish);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 

		return listItems;
	}
    
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean result = super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.dashboard_menu, menu);
		return result;
	}
    
    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent i;
		switch(item.getItemId()) {
		case R.id.map_search:
			onSearchRequested();
			return true;
		case R.id.map_preferences:
			showPreferences();
			return true;
		case R.id.map_refresh:
			refresh();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
    
    private void refresh() {
l = mLocationManager.getLastKnownLocation(mProvider);
        
        
        promotedDishes = this.fetchPromotedDishes();
        
        mNearestCanteenView.setText(nearName);
        mNearestCanteenView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent i = new Intent(getApplicationContext(), CanteenActivity.class);
				i.putExtra("name", nearName);
				i.putExtra("id", nearId);
				DashboardActivity.this.startActivity(i);
				
			}
        	
        });
        
        Gallery g = (Gallery) findViewById(R.id.offers_gallery);
        g.setAdapter(new ImageAdapter(this));
        
        g.setOnItemClickListener(new OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        		
        		Intent i = new Intent(getApplicationContext(),DishActivity.class);

				Dish dish = promotedDishes.get(position);
				i.putExtra("id", dish.getId());
				i.putExtra("name", dish.getName());

				DashboardActivity.this.startActivity(i);
        	}
        });
    }
    
    private void showPreferences() {
		Intent i = new Intent(this, SettingsActivity.class);
		startActivity(i);
	}
    
    private boolean isNetworkAvailable() {
	    ConnectivityManager connectivityManager 
	          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
	    return activeNetworkInfo != null;
	}
	
	
	/**
	 * Adapter class for Gallery view
	 */
    public class ImageAdapter extends BaseAdapter {
        private int mGalleryItemBackground;
        private Context mContext;

        public ImageAdapter(Context c) {
            mContext = c;
            TypedArray attr = mContext.obtainStyledAttributes(R.styleable.NearbyGalleryStyle);
            mGalleryItemBackground = attr.getResourceId(
            		R.styleable.NearbyGalleryStyle_android_galleryItemBackground, 0);
            attr.recycle();
        }
        
        public int getCount() {
            return promotedDishes.size();
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
        	float scale = mContext.getResources().getDisplayMetrics().density; 
        	int padding = 0;
        	
            ImageView imageView = new ImageView(mContext);
            imageView.setLayoutParams(new Gallery.LayoutParams(180, 180));
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            //imageView.setPadding(padding, padding, padding, padding);
            imageView.setBackgroundResource(mGalleryItemBackground);
            
            Dish dish = promotedDishes.get(position);
            
            if(dish.getImage() == null) {
				imageView.setImageResource(R.drawable.not_available);
			} else {
				try {
					imageView.setImageDrawable(Drawable.createFromStream(Utils.fetchImage(dish.getImage()), "src"));
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
			}

            return imageView;
        }
    }
    
    public class MyLocationListener implements LocationListener {
		public void onLocationChanged(Location location) {
			if (location != null) {
				l = location;
			}
		}

		public void onProviderDisabled(String provider) {
			mProvider = (provider == LocationManager.GPS_PROVIDER) ? LocationManager.NETWORK_PROVIDER
					: LocationManager.GPS_PROVIDER;
			Toast.makeText(getApplicationContext(), "Switch provider",
					Toast.LENGTH_SHORT);
		}

		public void onProviderEnabled(String provider) {
			mProvider = (provider == LocationManager.GPS_PROVIDER) ? LocationManager.GPS_PROVIDER
					: LocationManager.NETWORK_PROVIDER;
			Toast.makeText(getApplicationContext(), "Switch provider",
					Toast.LENGTH_SHORT);
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
			if (status != LocationProvider.AVAILABLE) {
				mProvider = (provider == LocationManager.GPS_PROVIDER) ? LocationManager.NETWORK_PROVIDER
						: LocationManager.GPS_PROVIDER;
			}
			Toast.makeText(getApplicationContext(), "Switch provider",
					Toast.LENGTH_SHORT);
		}
	}
    
        
}
